/*
 * @FilePath: socket_client.ts
 * @@author: wjj
 * @Date: 2024-12-05 10:44:41
 * @@Description: new js file
 */
import { defineStore } from 'pinia'
import type { socket_type } from './type'
import my_emitter from '@/utils/emitter'
import { ElNotification } from 'element-plus'
const useSocketClient = defineStore('socket-client', {
  // state: (): { socket_obj: WebSocketService | null; username: number } => {
  state: (): socket_type => {
    return {
      socket_obj: null,
      username: 0,
      // emitter: useEmit(),
    }
  },
  // TODO websocket实现
  getters: {},
  actions: {
    created(all_socket: any) {
      // 在created生命周期钩子函数中创建socket_obj
      console.log('created')
      this.socket_obj = all_socket
      if (this.socket_obj != null) {
        // this.socket_obj.onmessage = this.socketService
        this.socket_obj.onmessage = (event: any) => {
          if (this.socket_obj !== null && event.data) {
            const res = JSON.parse(event.data)
            if (res.code == 200) {
              if (res.emit_name) {
                // console.log(res.emit_name)
                //时间订阅
                my_emitter.emit(res.emit_name, res.data)
              }
            } else {
              ElNotification.error('长连接不存在')
            }
          }
        }
      }
    },
    //定义数据
    IOC_res_success(
      data: any = null,
      ioc_name: string = '',
      msg: string = 'success',
    ) {
      return {
        code: 200,
        msg: msg,
        ioc_name: ioc_name,
        data: data,
      }
    },
    IOC_res_error(
      data: any = null,
      ioc_name: string = '',
      msg: string = 'error',
    ) {
      return {
        code: 520,
        msg: msg,
        ioc_name: ioc_name,
        data: data,
      }
    },
  },
  // persist: {
  //   enable: true,// 启用持久化
  //   resetToState: true,
  // },
})
//对外暴露获取小仓库方法
export default useSocketClient
